<template>
  <div>
    <!-- 面包屑导航 S -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 面包屑导航 E -->
    <!-- 主体卡片区域 S -->
    <el-card class="box-card">
      <!-- 搜索框和添加用户按钮区域 S -->
      <el-row :gutter="20">
        <!-- 搜索框区域 S -->
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model.trim="queryData.query" clearable
            @clear="getUserList">
            <el-button slot="append" class="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <!-- 搜索框区域 E -->
        <!-- 添加用户按钮区域 S -->
        <el-col :span="4">
          <el-button type="primary" @click="addVisible=true">添加用户</el-button>
        </el-col>
        <!-- 添加用户按钮区域 E -->
      </el-row>
      <!-- 搜索框和添加用户按钮区域 E -->
      <template>
        <!-- 用户列表 S -->
        <el-table :data="userList" border style="width: 100%" stripe>
          <!-- 自增序号列 -->
          <el-table-column type="index" label="#">
          </el-table-column>
          <!-- 姓名列 -->
          <el-table-column prop="username" label="姓名">
          </el-table-column>
          <!-- 邮箱列 -->
          <el-table-column prop="email" label="邮箱">
          </el-table-column>
          <!-- 电话列 -->
          <el-table-column prop="mobile" label="电话">
          </el-table-column>
          <!-- 角色列 -->
          <el-table-column prop="role_name" label="角色">
          </el-table-column>
          <!-- 状态列 -->
          <el-table-column label="状态">
            <!-- 状态开关按钮 -->
            <template #default="{row}">
              <el-switch v-model="row.mg_state" active-color="#409eff" inactive-color="#dcdfe6"
                @change="updateUserState(row)">
              </el-switch>
            </template>
          </el-table-column>
          <!-- 操作按钮列  S -->
          <el-table-column label="操作" width="180">
            <template #default="{row}">
              <!-- 修改用户按钮 -->
              <el-button type="primary" size="mini" icon="el-icon-edit" @click="editUserInfo(row)">
              </el-button>
              <!-- 删除用户按钮 -->
              <el-button type="danger" size="mini" icon="el-icon-delete" @click="delUser(row.id)">
              </el-button>
              <!-- 分配角色按钮 -->
              <el-tooltip class="item" effect="dark" content="分配角色" placement="top"
                :enterable="false">
                <el-button type="warning" size="mini" icon="el-icon-setting"
                  @click="openEditRole(row)">
                </el-button>
              </el-tooltip>
            </template>
          </el-table-column>
          <!-- 操作按钮列  E -->
        </el-table>
        <!-- 分页器 -->
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="queryData.pagenum" :page-sizes="[2, 4, 8, 10]"
          :page-size="queryData.pagesize" layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
        <!-- 用户列表 E -->
      </template>
    </el-card>
    <!-- 主体卡片区域 E -->
    <!-- 添加用户的提示框 S -->
    <el-dialog title="添加用户" :visible.sync="addVisible" width="50%" @close="resrtForm('addForm')">
      <!-- 添加用户的表单 -->
      <el-form ref="addForm" :model="addForm" :rules="addRules" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password" type="password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 提示框按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser('addForm')">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加用户的提示框 E -->
    <!-- 修改用户的提示框 S -->
    <el-dialog title="修改用户" :visible.sync="editVisible" width="50%" @close="resrtForm('editForm')">
      <!-- 修改用户的表单 -->
      <el-form ref="editForm" :model="editForm" label-width="80px" :rules="editRules">
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 提示框按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser('editForm')">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户的提示框 E -->
    <!-- 分配角色的提示框 S -->
    <el-dialog title="修改用户" :visible.sync="editRoleVisible" width="50%" @close="resrtSelect">
      <!-- 分配角色的盒子内容 -->
      <div class="dialogBody">
        <p>当前的用户：{{editRoleUserinfo.username}}</p>
        <p>当前的角色：{{editRoleUserinfo.role_name}}</p>
        <div>
          分配新角色：
          <template>
            <el-select v-model="selectedRole" placeholder="请选择">
              <el-option v-for="item in roleList" :key="item.id" :label="item.roleName"
                :value="item.id">
              </el-option>
            </el-select>
          </template>
        </div>
      </div>
      <!-- 提示框按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRoleVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRole">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色的提示框 E -->
  </div>
</template>

<script>
// 校验手机号的规则函数
const checkMobile = (r, value, cb) => {
  const reg = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/
  if (reg.test(value)) return cb()
  cb(new Error())
}
export default {
  data() {
    return {
      userList: [], // 用户列表
      // 查询用户列表的数据对象
      queryData: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      // 总数据条数
      total: 0,
      // 添加用户的提示框开关
      addVisible: false,
      // 添加用户的表单数据
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 添加用户的表单校验规则
      addRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, message: '请输入正确的手机号', trigger: ['blur', 'change'] }
        ]
      },
      // 修改用户提示框的开关
      editVisible: false,
      // 修改用户的表单数据
      editForm: {
        id: null,
        username: '',
        email: '',
        mobile: ''
      },
      // 修改用户表单的校验规则
      editRules: {
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, message: '请输入正确的手机号', trigger: ['blur', 'change'] }
        ]
      },
      // 分配角色提示框开关
      editRoleVisible: false,
      // 点击分配角色后当前用户本身的数据
      editRoleUserinfo: {
        id: null,
        username: '',
        role_name: ''
      },
      // 所有角色列表
      roleList: [],
      // 选择的角色
      selectedRole: ''
    }
  },

  created() {
    // 获取用户列表
    this.getUserList()
  },

  methods: {
    // 获取用户列表
    async getUserList() {
      const data = await this.$axios.get('/users', { params: this.queryData })
      if (data.meta.status !== 200) return this.$message.error('获取用户列表失败!')
      this.userList = data.data.users
      this.total = data.data.total
    },
    // 分页器选择每页显示几条数据
    handleSizeChange(pagesize) {
      this.queryData.pagesize = pagesize
      this.getUserList()
    },
    // 分页器选择第几页
    handleCurrentChange(pagenum) {
      this.queryData.pagenum = pagenum
      this.getUserList()
    },
    // 更新用户状态
    async updateUserState(user) {
      const data = await this.$axios.put(`users/${user.id}/state/${user.mg_state}`)
      if (data.meta.status !== 200) return this.$message.error('修改用户状态失败！')
      this.$message.success('修改用户状态成功~')
    },
    // 重置表单
    resrtForm(formName) {
      this.$refs[formName].resetFields()
    },
    // 添加用户
    addUser(formName) {
      this.$refs[formName].validate(async valid => {
        if (!valid) return
        const data = await this.$axios.post('users', this.addForm)
        if (data.meta.status !== 201) return this.$message.error('添加用户失败!')
        this.addVisible = false
        this.$message.success('添加用户成功~')
        this.getUserList()
      })
    },
    // 点击修改用户按钮后 根据id获取用户信息
    editUserInfo(row) {
      this.editVisible = true
      this.editForm.id = row.id
      this.editForm.username = row.username
      this.editForm.email = row.email
      this.editForm.mobile = row.mobile
    },
    // 修改用户
    editUser(formName) {
      this.$refs[formName].validate(async valid => {
        if (!valid) return
        const { meta } = await this.$axios.put(`/users/${this.editForm.id}`, {
          email: this.editForm.email,
          mobile: this.editForm.mobile
        })
        if (meta.status !== 200) return this.$message.error('修改用户信息失败！')
        this.$message.success('修改用户信息成功~')
        this.editVisible = false
        this.getUserList()
      })
    },
    // 删除用户
    delUser(id) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { meta } = await this.$axios.delete(`/users/${id}`)
          if (meta.status !== 200) return this.$message.error('删除失败！')
          this.$message.success('删除成功!')
          this.getUserList()
        })
        .catch(() => {
          this.$message.info('已取消删除')
        })
    },
    // 点击分配角色后 打开分配角色的提示框
    async openEditRole(u) {
      this.editRoleVisible = true
      this.editRoleUserinfo.username = u.username
      this.editRoleUserinfo.role_name = u.role_name
      this.editRoleUserinfo.id = u.id
      const data = await this.$axios.get('/roles')
      if (data.meta.status !== 200) return this.$message.error('获取角色列表失败！')
      this.roleList = data.data
    },
    // 提交分配角色
    async editRole() {
      if (!this.selectedRole) return this.$message.error('请选择角色！')
      const res = await this.$axios.put(`users/${this.editRoleUserinfo.id}/role`, { rid: this.selectedRole })
      if (res.meta.status !== 200) return this.$message.error('分配角色失败！')
      this.$message.success('分配角色成功~')
      this.editRoleVisible = false
      this.getUserList()
    },
    // 分配角色提示框关闭后执行
    resrtSelect() {
      this.selectedRole = ''
    }
  }
}
</script>

<style scoped lang='less'>
.dialogBody {
  p {
    margin: 14px 0;
  }
}
</style>
